package com.gtlab1207.br_awareness.ctrls;


import com.gtlab1207.br_awareness.common.Codes;
import com.gtlab1207.br_awareness.common.PageUtil;
import com.gtlab1207.br_awareness.common.Result;
import com.gtlab1207.br_awareness.models.domain.LogHost;
import com.gtlab1207.br_awareness.services.LogHostService;
import com.gtlab1207.br_awareness.services.LogRecordService;
import com.gtlab1207.br_awareness.services.LogRecordWriteTimerTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Timer;

/**
 * 主机信息业务控制层
 */
@RestController
@RequestMapping("/api/logHost")
public class LogHostCtrl extends BaseCtrl {
    @Autowired
    private LogHostService logHostService;
    @Autowired
    LogRecordWriteTimerTask logRecordWriteTimerTask;
    @Autowired
    LogRecordService logRecordService;

    /**
     * 获取主机信息列表
     * @param ipAddress 主机ip地址
     * @param isActivate 是否启用日志扫描
     * @param pageNum 分页当前页
     * @param pageSize 分页每页展示数量
     * @return
     */
    @GetMapping("/info")
    public Result selectLogHost(@RequestParam(value = "ipAddress", required = false) String ipAddress,
                                @RequestParam(value = "isActivate", required = false) String isActivate,
                                @RequestParam(value = "pageNum",defaultValue ="1")Integer pageNum,
                                @RequestParam(value = "pageSize",defaultValue ="5")Integer pageSize){
        try {
            Map<String, Object> params = PageUtil.setPageInfo(pageNum, pageSize);//设置分页参数
            params.put("ipAddress",ipAddress);
            params.put("isActivate",isActivate);
            Map<String, Object> map = logHostService.selectLogHost(params, pageSize);
            return this.send(map);
        } catch (Exception e) {
            e.printStackTrace();
            return this.send(Codes.FAILED);
        }
    }

    /**
     * 新增主机信息
     * @param logHost
     * @return
     */
    @PostMapping("/info")
    public Result insertLogHost(@Valid LogHost logHost){
        try {
            if(logHost.getIpAddress()!=null&&!logHost.getIpAddress().equals("")){
                LogHost logHost1 = logHostService.getLogHostByIp(logHost.getIpAddress());
                if(logHost1!=null){
                    return this.send(Codes.MACHINE_EXIST);
                }
            }
            int result = logHostService.insertLogHost(logHost);
            if (result == 0) {
                return send(Codes.FAILED);
            }else if(result == -1)
                return send(Codes.AUTHENTICATION_FAILED);
            return this.send(Codes.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return this.send(Codes.FAILED);
        }
    }

    /**
     * 更新主机信息
     * @param logHost
     * @return
     */
    @PutMapping("/info")
    public Result deleteLogHost(LogHost logHost){
        try {
            int result = logHostService.updateLogHost(logHost);
            if (result == 0) {
                return send(Codes.NO_EXIST);
            }
            return this.send(Codes.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return this.send(Codes.FAILED);
        }
    }

    /**
     * 删除主机信息
     * @param id
     * @return
     */
    @DeleteMapping("/info/{id}")
    public Result deleteLogHost(@PathVariable Integer id){
        try {
            int result = logHostService.deleteLogHost(id);
            if (result == 0) {
                return send(Codes.NO_EXIST);
            }
            return this.send(Codes.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return this.send(Codes.FAILED);
        }
    }

    /**
     * 主机启用日志扫描
     * @param id
     * @return
     */
    @PutMapping("/activate")
    public Result hostActivate(@RequestParam(value = "id") Integer id){
        try {
            int result = logHostService.hostActivate(id);
            if (result == 0) {
                return send(Codes.NO_EXIST);
            }
            return this.send(Codes.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return this.send(Codes.FAILED);
        }
    }

    /**
     * 主机关闭日志扫描
     * @param id
     * @return
     */
    @PutMapping("/deactivate")
    public Result hostDeactivate(@RequestParam(value = "id") Integer id){
        try {
            int result = logHostService.hostDeactivate(id);
            if (result == 0) {
                return send(Codes.NO_EXIST);
            }
            return this.send(Codes.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return this.send(Codes.FAILED);
        }
    }

    /**
     * 伴随启动日志写入程序
     */
    @PostConstruct
    public void logRecordTimer(){
        Timer timer = new Timer();
        // 当前时间开始
        Date startDate = new Date();
        long period = 24*60*60*1000;    // 默认1天读取一次
        timer.schedule(logRecordWriteTimerTask, startDate, period);
    }

    @GetMapping("/log")
    public Result startLogScanning(){
        //写入前删除大于七天的数据
        logRecordService.deleteLogRecord();
        List<LogHost> logHostList = logHostService.getActivatedLogHost();
        if (logHostList != null && logHostList.size() > 0) {
            for (LogHost i : logHostList) {
                logHostService.updateLastScanTime(i.getId());
                logRecordService.writeSuricataLog(i);
                logRecordService.writeSecurityLog(i);
                logRecordService.writeSystemLog(i);
            }
            return this.send(Codes.SUCCESS);
        }
        return send(Codes.NO_MACHINE_EXIST);
    }
}
